package com.hbnu.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import java.util.Random;

@Slf4j
@Component
public class EmailUtil{

    private final JavaMailSender javaMailSender;

    private final String fromEmail;

    public EmailUtil(JavaMailSender javaMailSender,@Value("${spring.mail.username}") String fromEmail) {
        this.javaMailSender = javaMailSender;
        this.fromEmail = fromEmail;
    }

    public String sendCode(String to,String str,String code) {
        SimpleMailMessage  message = new SimpleMailMessage();
        message.setFrom(fromEmail);
        message.setTo(to);
        message.setSubject(str);
        message.setText("您的验证码是："+code+"该验证码5分钟内有效，请妥善保管，切勿泄露。");
        javaMailSender.send(message);
        return code;
    }
    public String getCode(){
        StringBuilder sb =new StringBuilder();
        for (int i = 0; sb.length()<6; i++) {
            int num=new Random().nextInt(10);
            sb.append(num);
        }
        return sb.toString();
    }
}
